package xyz.luhui1hao.rxjava2andretrofit2.api.http;

import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static xyz.luhui1hao.rxjava2andretrofit2.BuildConfig.API_BASE_URL;

public class Api {

    private static final long TIME_OUT = 5000;
    public static ApiService apiService;

    //单例
    public static ApiService getApiService() {
        if (apiService == null) {
            synchronized (Api.class) {
                if (apiService == null) {
                    new Api();
                }
            }
        }
        return apiService;
    }

    private OkHttpClient okHttpClient = new OkHttpClient
            .Builder()
            .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
            //添加应用拦截器
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    //获取request
                    Request request = chain.request();
                    //从request中获取原有的HttpUrl实例oldHttpUrl
                    HttpUrl oldHttpUrl = request.url();
                    //获取request的创建者builder
                    Request.Builder builder = request.newBuilder();
                    //从request中获取headers，通过给定的键url_name
                    List<String> headerValues = request.headers("bqs_auth");
                    if (headerValues != null && headerValues.size() > 0) {
                        //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
                        builder.removeHeader("bqs_auth");
                        //匹配获得新的BaseUrl
                        String headerValue = headerValues.get(0);
                        HttpUrl newBaseUrl = null;
                        if ("douban".equals(headerValue)) {
                            newBaseUrl = HttpUrl.parse("http://api.douban.com");
                        } else {
                            newBaseUrl = oldHttpUrl;
                        }
                        //重建新的HttpUrl，修改需要修改的url部分
                        HttpUrl newFullUrl = oldHttpUrl
                                .newBuilder()
                                .scheme(newBaseUrl.scheme())//更换网络协议
                                .host(newBaseUrl.host())//更换主机名
                                .port(newBaseUrl.port())//更换端口
                                .build();
                        //重建这个request，通过builder.url(newFullUrl).build()；
                        // 然后返回一个response至此结束修改
                        Log.e("Url", "intercept: " + newFullUrl.toString());
                        return chain.proceed(builder.url(newFullUrl).build());
                    }
                    return chain.proceed(request);
                }
            })
            .build();

    private Api() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())//请求的结果转为实体类
                //适配RxJava2.0,RxJava1.x则为RxJavaCallAdapterFactory.create()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }
}
